package priv.conceit.sc.hoxton.auth.core;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;
import priv.conceit.sc.hoxton.common.web.security.WebAccessDeniedHandler;
import priv.conceit.sc.hoxton.common.web.security.WebAuthenticationEntryPoint;

import javax.annotation.Resource;

/**
 * sc.hoxton
 *
 * @author Conceit
 * 2019/9/20 增加方法
 * @since 1.0.0, 2019/9/20
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@SuppressWarnings("all")
public class AuthConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private TokenFilter tokenFilter;

	@Autowired
	private UserDetailsService userDetailsServiceImpl;

	@Autowired
	private WebAuthenticationEntryPoint webAuthenticationEntryPoint;

	@Autowired
	private WebAccessDeniedHandler webAccessDeniedHandler;


	@Override
	protected void configure(HttpSecurity http) throws Exception {

		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry
				= http.authorizeRequests();
		registry.requestMatchers(CorsUtils::isPreFlightRequest).permitAll();

		http.csrf().disable();

		http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

		http.exceptionHandling().authenticationEntryPoint(this.webAuthenticationEntryPoint);

		http.exceptionHandling().accessDeniedHandler(this.webAccessDeniedHandler);

		http.userDetailsService(this.userDetailsServiceImpl);
		http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);

		http.authorizeRequests().anyRequest().authenticated();
		http.headers().cacheControl().disable();
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/css/**")
				.antMatchers("/instances")
				.antMatchers("/actuator/**")
				.antMatchers("/authority/user/login/**")
				.antMatchers("/authority/user/token/verify/**");
	}

}
